package cn.com.api.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.com.api.entity.ApiDingDan;
import cn.com.api.entity.ApiShop;
import cn.com.api.entity.ApiT_dingdan;
import cn.com.api.entity.ApiT_shipping;
import cn.com.api.entity.T_unnormal_orders;
import cn.com.api.mapper.ApiDingDanMapper;
import cn.com.api.mapper.ApiShopsMapper;
import cn.com.api.mapper.ApiT_dingdanMapper;
import cn.com.api.mapper.ApiT_shippingMapper;
import cn.com.api.mapper.ApiT_statsMapper;
import cn.com.api.mapper.ApiT_unnormalMapper;
import cn.com.api.service.ApiT_dingdanService;
import cn.com.api.service.impl.base.T_dingdanServiceImplBase;
import cn.com.util.DateUtil;
/*import cn.com.web.mapper.MemberMapper;*/
import cn.com.util.Util;

/**
 * 
 **/
@Service
public class ApiT_dingdanServiceImpl extends T_dingdanServiceImplBase implements ApiT_dingdanService {
	@Autowired
	private ApiDingDanMapper dingDanMapper;
	@Autowired
	private ApiT_dingdanMapper apiT_dingdanMapper;
	@Autowired
	private ApiShopsMapper apiShopsMapper;
	/*
	 * @Autowired private MemberMapper memberMapper;
	 */
	@Autowired
	private ApiT_shippingMapper apiT_shippingMapper;
	@Autowired
	private ApiT_unnormalMapper apiT_unnormalMapper;
	@Autowired
	private ApiT_statsMapper apiT_statsMapper;

	@Override
	public ApiT_dingdan findDingDan(ApiT_dingdan conditions) {
		return apiT_dingdanMapper.findDingDan(conditions);
	}

	@Override
	public ApiT_dingdan findDingDanInfo(int id) {
		ApiT_dingdan conditions = new ApiT_dingdan();
		conditions.setRid(id);
		return apiT_dingdanMapper.findDingDanInfo(conditions);
	}

	@Override
	public int updateDingdan(ApiT_dingdan newdingdan) {
		return apiT_dingdanMapper.updateDingdan(newdingdan);
	}

	@Override
	// 根据订单titles查询订单详情
	public ApiT_dingdan findbytitles(String titles) {

		return apiT_dingdanMapper.findbytitles(titles);
	}

	@Override
	public List<ApiT_dingdan> batchDingDansInfo(Integer[] rids) {
		ApiT_dingdan conditions = new ApiT_dingdan();
		conditions.setRids(rids);
		return apiT_dingdanMapper.batchDingDansInfo(conditions);
	}

	@Override
	public int batchUpdateDingdanPrintStatus(Integer[] rids) {
		ApiT_dingdan conditions = new ApiT_dingdan();
		conditions.setRids(rids);
		conditions.setIs_print(1);
		return apiT_dingdanMapper.batchUpdateDingdan(conditions);
	}

	@Override
	@Transactional
	public Map<String, Object> cancleOrder(String orderId, String duty, String remark) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		ApiDingDan dingdan = dingDanMapper.searchDingDanByTitleId(orderId);
		ApiShop shop = apiShopsMapper.findShopByCid(dingdan.getShop_id() + "");

		if (dingdan.getEnable() == 2 || dingdan.getEnable() == 4) {
			result.put("error", "003");
			result.put("information", "订单已被取消,不能重复取消");
			return result;
		}

		if (dingdan.getEnable() == 3) {
			result.put("error", "004");
			result.put("information", "订单已退货,不能取消");
			return result;
		}

		// 更改订单状态为取消状态
		ApiT_dingdan newDingDan = new ApiT_dingdan();
		newDingDan.setRid(dingdan.getRid());
		newDingDan.setEnable(4);// 取消状态
		if (dingdan.getZi_status() == 1) {// 已经支付完时
			newDingDan.setZi_status(2);// 支付状态改为退款
		}
		newDingDan.setCancle_time(DateUtil.nowTimeToString());
		newDingDan.setCancelreason(remark);
		apiT_dingdanMapper.updateDingdan(newDingDan);

		ApiT_shipping shipping = apiT_shippingMapper.findT_shippingByOrderId(orderId);

		DecimalFormat df = new DecimalFormat("######0.00");
		int is_recieve_box_money = shop.getIs_recieve_box_money();// 当日餐盒费是否结算给商家
		BigDecimal lunchbox_price = dingdan.getLunchbox_price();
		BigDecimal money = BigDecimal.ZERO;// 结算给商家的钱
		BigDecimal moneyWithOutSeedFee = dingdan.getMoney().subtract(dingdan.getSendFee());

		if (is_recieve_box_money == 1) {// 1：商家收餐盒费;
			money = moneyWithOutSeedFee.multiply(Util.getBigDecimal(shop.getDiscount().toString()));
			// money = ArithUtil.mul(moneyWithOutSeedFee,
			// Double.parseDouble(shop.getDiscount()));//商铺所得金额
		} else if (is_recieve_box_money == 2) {// 2：平台收餐盒费
			money = (moneyWithOutSeedFee.subtract(lunchbox_price))
					.multiply(Util.getBigDecimal(shop.getDiscount().toString()));
			// money = ArithUtil.mul(ArithUtil.sub(moneyWithOutSeedFee,
			// lunchbox_price), Double.parseDouble(shop.getDiscount()));//商铺所得金额
		} else {
			money = moneyWithOutSeedFee.multiply(Util.getBigDecimal(shop.getDiscount().toString()));
			// money = ArithUtil.mul(moneyWithOutSeedFee,
			// Double.parseDouble(shop.getDiscount()));//商铺所得金额
		}

		int zfType = Integer.parseInt(dingdan.getZf_type());
		if (dingdan.getZi_status() == 1 && (zfType == 0 || zfType == 1 || zfType == 2)) {// 在线支付返回到用户余额
			Map<String, Object> info = new HashMap<String, Object>();
			String uid = dingdan.getU_id();
			/* info=memberMapper.selectInfoByUid(uid); */
			BigDecimal dmoney = dingdan.getPayMoney();
			Double ye = Double.parseDouble(info.get("c_money") + "");
			/*
			 * memberMapper.updateMoney(df.format(dmoney+ye), uid);//更新用户余额
			 */
			if (shipping == null || shipping.getUser_id() == null) {// 还没有分配配送员
				result.put("error", "0000");
				result.put("information", "操作成功");
				return result;
			}

			if (shop.getIs_ziying() == 1) {// 自营的取消订单
				if ("1".equals(duty)) {// 责任方是商家

				} else if ("2".equals(duty)) {// 责任方是配送员
					T_unnormal_orders unnormalOrder = new T_unnormal_orders();
					unnormalOrder.setOrder_id(orderId);
					unnormalOrder.setCreate_time(DateUtil.nowTimeToString());
					unnormalOrder.setDuty(2);
					unnormalOrder.setShipper_money(dmoney);// 配送员要赔的钱
					unnormalOrder.setShop_money(BigDecimal.ZERO);
					unnormalOrder.setShipper_id(shipping.getUser_id());
					unnormalOrder.setShop_id(dingdan.getShop_id());
					unnormalOrder.setType(2);// 取消订单
					unnormalOrder.setRemark(remark);
					apiT_unnormalMapper.insertUnnoralOrder(unnormalOrder);
				}
			} else {// 非自营的取消订单
				if ("1".equals(duty)) {// 责任方是商家
					if (isCountUp(shipping.getArrive_user_time())) {// 订单完成时期
																	// 已被统计（记录已插入统计表）
						// 记录商家应该减少的钱
						T_unnormal_orders unnormalOrder = new T_unnormal_orders();
						unnormalOrder.setOrder_id(orderId);
						unnormalOrder.setCreate_time(DateUtil.nowTimeToString());
						unnormalOrder.setDuty(1);
						unnormalOrder.setShop_money(money);// 商家要减少的钱
						unnormalOrder.setShipper_money(BigDecimal.ZERO);
						unnormalOrder.setShipper_id(shipping.getUser_id());
						unnormalOrder.setShop_id(dingdan.getShop_id());
						unnormalOrder.setType(2);
						unnormalOrder.setRemark(remark);
						apiT_unnormalMapper.insertUnnoralOrder(unnormalOrder);
					} else {// 没有统计过

					}

				} else if ("2".equals(duty)) {// 责任方是配送员 继续将钱算给商家
					if (isCountUp(shipping.getArrive_user_time())) {// 订单完成时期
																	// 已被统计（记录已插入统计表）
						// 保存配送员需要赔偿的钱 （商铺的钱已统计进入了统计表）
						T_unnormal_orders unnormalOrder = new T_unnormal_orders();
						unnormalOrder.setOrder_id(orderId);
						unnormalOrder.setCreate_time(DateUtil.nowTimeToString());
						unnormalOrder.setDuty(2);
						unnormalOrder.setShop_money(BigDecimal.ZERO);// 商家能收到的钱（已统计过）
						unnormalOrder.setShipper_money(dmoney);// 配送员要赔的钱
						unnormalOrder.setShipper_id(shipping.getUser_id());
						unnormalOrder.setShop_id(dingdan.getShop_id());
						unnormalOrder.setType(2);
						unnormalOrder.setRemark(remark);

						apiT_unnormalMapper.insertUnnoralOrder(unnormalOrder);
					} else {
						// 保存商家能收到的钱，配送员要赔的钱
						T_unnormal_orders unnormalOrder = new T_unnormal_orders();
						unnormalOrder.setOrder_id(orderId);
						unnormalOrder.setCreate_time(DateUtil.nowTimeToString());
						unnormalOrder.setDuty(2);
						unnormalOrder.setShop_money(money);// 商家能收到的钱
						unnormalOrder.setShipper_money(dmoney);// 配送员要赔的钱
						unnormalOrder.setShipper_id(shipping.getUser_id());
						unnormalOrder.setShop_id(dingdan.getShop_id());
						unnormalOrder.setType(2);
						unnormalOrder.setRemark(remark);

						apiT_unnormalMapper.insertUnnoralOrder(unnormalOrder);
					}
				}
			}
		} else {// 货到付款

			if (shipping == null || shipping.getUser_id() == null) {// 还没有分配配送员
				result.put("error", "0000");
				result.put("information", "操作成功");
				return result;
			}

			if (shop.getIs_ziying() == 1) {// 自营的
				if (shipping.getStatus() == 6) {// 货已送达（配送员已经收到钱），把钱打到用户帐户余额里
					Map<String, Object> info = new HashMap<String, Object>();
					String uid = dingdan.getU_id();
					/* info=memberMapper.selectInfoByUid(uid); */
					BigDecimal dmoney = dingdan.getPayMoney();
					Double ye = Double.parseDouble(info.get("c_money") + "");
					/*
					 * memberMapper.updateMoney(df.format(dmoney+ye),
					 * uid);//更新用户余额
					 */

					if ("1".equals(duty)) {// 责任方是商家

					} else if ("2".equals(duty)) {// 责任方是配送员
						T_unnormal_orders unnormalOrder = new T_unnormal_orders();
						unnormalOrder.setOrder_id(orderId);
						unnormalOrder.setCreate_time(DateUtil.nowTimeToString());
						unnormalOrder.setDuty(2);
						unnormalOrder.setShipper_money(dmoney);// 配送员要赔的钱
						unnormalOrder.setShop_money(BigDecimal.ZERO);
						unnormalOrder.setShipper_id(shipping.getUser_id());
						unnormalOrder.setShop_id(dingdan.getShop_id());
						unnormalOrder.setType(2);
						unnormalOrder.setRemark(remark);

						apiT_unnormalMapper.insertUnnoralOrder(unnormalOrder);
					}
				}
			} else {// 非自营的
				if ("1".equals(duty)) {// 责任方是商家
					// TODO 隔天的订单待 更新统计表记录
					// 代表配送员已经收到钱了
					if (shipping.getStatus() == 6) {// 货已送达（配送员已经收到钱），把钱打到用户帐户余额里
						Map<String, Object> info = new HashMap<String, Object>();
						String uid = dingdan.getU_id();
						/* info=memberMapper.selectInfoByUid(uid); */
						BigDecimal dmoney = dingdan.getPayMoney();
						Double ye = Double.parseDouble(info.get("c_money") + "");
						/*
						 * memberMapper.updateMoney(df.format(dmoney+ye),
						 * uid);//更新用户余额
						 */
						if (isCountUp(shipping.getArrive_user_time())) {
							// 记录商家应该减少的钱
							T_unnormal_orders unnormalOrder = new T_unnormal_orders();
							unnormalOrder.setOrder_id(orderId);
							unnormalOrder.setCreate_time(DateUtil.nowTimeToString());
							unnormalOrder.setDuty(1);
							unnormalOrder.setShop_money(money);// 商家要减少的钱
							unnormalOrder.setShipper_money(BigDecimal.ZERO);
							unnormalOrder.setShipper_id(shipping.getUser_id());
							unnormalOrder.setShop_id(dingdan.getShop_id());
							unnormalOrder.setType(2);
							unnormalOrder.setRemark(remark);

							apiT_unnormalMapper.insertUnnoralOrder(unnormalOrder);
						} else {
							System.out.println(">>>>>>>>>>>");
						}
					}

				} else if ("2".equals(duty)) {// 责任方是配送员 继续将钱算给商家
					// 代表配送员已经收到钱了
					if (shipping.getStatus() == 6) {// 货已送达（配送员已经收到钱），把钱打到用户帐户余额里
						Map<String, Object> info = new HashMap<String, Object>();
						String uid = dingdan.getU_id();
						/* info=memberMapper.selectInfoByUid(uid); */
						BigDecimal dmoney = dingdan.getPayMoney();
						Double ye = Double.parseDouble(info.get("c_money") + "");
						/*
						 * memberMapper.updateMoney(df.format(dmoney+ye),
						 * uid);//更新用户余额
						 */
						if (isCountUp(shipping.getArrive_user_time())) {

						} else {
							// 保存配送员需要赔偿的钱 （商铺的钱已统计进入了统计表）
							T_unnormal_orders unnormalOrder = new T_unnormal_orders();
							unnormalOrder.setOrder_id(orderId);
							unnormalOrder.setCreate_time(DateUtil.nowTimeToString());
							unnormalOrder.setDuty(2);
							unnormalOrder.setShop_money(money);// 商家能收到的钱
							unnormalOrder.setShipper_money(dingdan.getPayMoney());// 配送员要赔的钱
							unnormalOrder.setType(2);
							unnormalOrder.setRemark(remark);

							apiT_unnormalMapper.insertUnnoralOrder(unnormalOrder);
						}
					}

				}
			}
		}

		result.put("error", "0000");
		result.put("information", "操作成功");

		return result;
	}

	/**
	 * 是否已经统计
	 * 
	 * @param strDate
	 *            "yyyy-MM-dd HH:mm:ss"
	 * @return
	 * @throws Exception
	 */
	private boolean isCountUp(Date date) throws Exception {
		if (date == null) {
			return false;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		int count = apiT_statsMapper.getDateByTime(year, month, day);

		if (count > 0) {
			return true;
		} else {
			return false;
		}
	}

}
